<template>
    <div class="employees-list-page">
        <el-card shadow="never" class="mt-4">
            <el-tabs v-model="activeName" type="card">
                <el-tab-pane label="企业微信" name="weixin"></el-tab-pane>
                <el-tab-pane label="钉钉" name="dingtalk"></el-tab-pane>
            </el-tabs>

            <template v-if="my.wx_work_corpid || activeName === 'dingtalk'">
            <el-button :disabled="!selectionList.length" type="primary" @click="onDialogPass">通过</el-button>
            <div class="mt-4" v-loading="loading">
                <el-table ref="table" :data="data" @selection-change="handleSelectionChange" :row-key="rowKey">
                    <el-table-column
                        type="selection"
                        :selectable="selectInit"
                        reserve-selection
                        width="55"/>
                    <el-table-column label="序号" type="index"/>
                    <el-table-column label="员工姓名" prop="name"/>
                    <el-table-column label="员工头像">
                        <template slot-scope="{row}">
                            <img class="w-16 h-16" :src="row.avatar" alt="">
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="{row}">
                            <span class="text-blue-600" v-if="row.status === 3">已通过</span>
                            <div v-else>
                                <el-button
                                    :disabled="!!selectionList.length"
                                    type="primary"
                                    @click="onDialogPass(row.id)">通过</el-button>
                                <el-button
                                    :disabled="!!selectionList.length"
                                    type="primary"
                                    @click="onDialog(row.id)">绑定已有员工</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <div v-if="totalElements" class="footer">
                    <el-pagination
                        class="center"
                        @current-change="fetchData"
                        :current-page.sync="form.page"
                        :page-size="form.size"
                        :page-sizes="[10, 25, 50]"
                        layout="total, prev, pager, next, sizes, jumper"
                        :total="totalElements">
                    </el-pagination>
                </div>
            </div>
            </template>

            <div v-if="!my.wx_work_corpid && activeName ==='weixin'">
                <el-button>
                    <router-link to="/permission/bind/account">绑定企业微信帐号</router-link>
                </el-button>
            </div>
        </el-card>

        <el-dialog
            title="选择已有用户"
            :visible.sync="visible"
            width="60%">
            <div v-loading="loading">
                <el-table :data="disalogList">
                    <el-table-column label="序号" type="index"/>
                    <el-table-column label="员工姓名" prop="name"/>
                    <el-table-column label="账号" prop="email"/>
                    <el-table-column label="操作">
                        <template slot-scope="{row}">
                            <el-button
                                v-if="activeName === 'weixin' ? !row.is_bind_wx_work : !row.is_bind_ding"
                                type="primary"
                                @click="onBindClick(row.id)">选择</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div v-if="disalogForm.total" class="footer">
                    <el-pagination
                        class="center"
                        @current-change="fetchUser"
                        :current-page.sync="disalogForm.page"
                        :page-size="disalogForm.size"
                        :page-sizes="[10, 25, 50]"
                        layout="total, prev, pager, next, sizes, jumper"
                        :total="disalogForm.total">
                    </el-pagination>
                </div>
            </div>
        </el-dialog>

        <el-dialog
            title="审核"
            :visible.sync="visibles"
            width="60%">
            <div v-loading="loading">
                <div class="mb-4" v-if="selectionList.length">当前所选审核账号数量：{{ selectionList.length }}</div>
                <label class="mr-2">请选择账号配额：</label>
                <el-select
                    v-model="passForm.application_id"
                    clearable>
                    <el-option
                        v-for="item in applicationOptions"
                        :key="item.id"
                        :disabled="selectionList.length > (item.count - item.used_count)"
                        :label="`激活${selectionList.length || 1}个账号配额。
                        （激活后还有 ${applicationLabel(item, selectionList.length)} 个，
                        每个可用${item.duration}天的账号配额 ）`"
                        :value="item.id">
                    </el-option>
                </el-select>
                <div class="text-center mt-4">
                    <el-button type="primary" :disabled="!passForm.application_id" @click="onPassClick">确 定</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { Tabs, TabPane } from 'element-ui';

export default {
    components: {
        ElTabs: Tabs,
        ElTabPane: TabPane,
    },
    mixins: [require('@/mixins/CacheQuery').default],
    data() {
        return {
            loading: false,
            visible: false,
            visibles: false,
            data: [],
            form: {
                page: 1,
                size: 10,
            },
            totalElements: 0,

            // 绑定已有用户
            disalogForm: {
                page: 1,
                size: 10,
                total: 0,
                id: '',
            },
            disalogList: [],

            // 审核
            passForm: {
                id: '',
                application_id: '',
            },
            applicationOptions: [],
            selectionList: [],

            my: '',

            activeName: 'weixin',
        };
    },
    watch: {
        visibles(val) {
            if (!val) {
                this.passForm.id = '';
                this.passForm.application_id = '';
            }
        },
        activeName() {
            this.data = [];
            this.form.page = 1;
            this.selectionList = [];
            const tables = this.$refs.table;
            if (tables) tables.clearSelection();
            this.fetchData();
        },
    },
    methods: {
        fetchData() {
            const dingT = this.activeName === 'dingtalk' ? 'ding_' : '';

            this.loading = true;
            API.get(`${dingT}company_check`, { params: this.form }).then((res) => {
                this.data = res.content;
                this.totalElements = res.pagination.total;
            }).finally(() => {
                this.loading = false;
            });
        },

        fetchUser() {
            this.loading = true;
            API.get('user', { params: this.disalogForm }).then((res) => {
                this.disalogList = res.content;
                this.disalogForm.total = res.pagination.total;
            }).finally(() => this.loading = false);
        },

        fetchApplicationData() {
            this.loading = true;
            API.get('account/application/list').then((res) => {
                this.applicationOptions = res.filter(option => option.count > option.used_count);
            }).finally(() => this.loading = false);
        },

        // 绑定已有用户
        onBindClick(userId) {
            $ele.$confirm('是否选择此用户？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                const dingT = this.activeName === 'dingtalk' ? 'ding_' : '';
                this.loading = true;
                API.post(`${dingT}company_check/check_pass`, {
                    id: this.disalogForm.id,
                    user_id: userId,
                    is_relation: true,
                }).then(() => {
                    $ele.$message.success('绑定成功');
                    this.onDialog();
                    this.fetchData();
                }).finally(() => this.loading = false);
            }).catch(() => { });
        },
        // 弹窗
        onDialog(id) {
            this.visible = !this.visible;
            if (id) this.disalogForm.id = id;
        },

        // 审核通过
        onPassClick() {
            const selectionNum = this.selectionList.length;
            $ele.$confirm(
                `此操作会生成新账号且使用${selectionNum || 1}个账号配额，是否通过此申请？`,
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                },
            ).then(() => {
                let url;
                let form;
                const dingT = this.activeName === 'dingtalk' ? 'ding_' : '';
                if (!selectionNum) {
                    url = `${dingT}company_check/check_pass`;
                    form = {
                        id: this.passForm.id,
                        is_relation: false,
                        application_id: this.passForm.application_id,
                    };
                } else {
                    url = `${dingT}company_check/batch_check`;
                    form = {
                        application_id: this.passForm.application_id,
                        ids: this.selectionList,
                    };
                }

                this.loading = true;
                API.post(url, form).then(() => {
                    $ele.$message.success('操作成功');
                    this.onDialogPass();
                    this.fetchData();
                    this.fetchApplicationData();
                    this.$refs.table.clearSelection();
                }).finally(() => this.loading = false);
            }).catch(() => { });
        },
        // 弹窗
        onDialogPass(id) {
            this.visibles = !this.visibles;
            if (id) this.passForm.id = id;
        },

        // 禁用
        selectInit(row) {
            return row.status !== 3;
        },
        rowKey(row) {
            return row.id;
        },
        // 复选框选择
        handleSelectionChange(val) {
            if (val && val.length) {
                const ids = [];
                for (const item of val) {
                    ids.push(item.id);
                }
                this.selectionList = ids;
            } else this.selectionList = [];
        },

        applicationLabel(item, selectionNum) {
            const num = item.count - item.used_count - (selectionNum || 1);
            return num >= 0 ? num : `0 个，配额不足！还需 ${Math.abs(num)}`;
        },
    },
    mounted() {
        const my = this.$store.state.my;
        this.my = my;

        if (my.wx_work_corpid) this.fetchData();
        this.fetchUser();
        this.fetchApplicationData();
    },
};
</script>

<style lang="scss">
.employees-list-page {
    .filter {
        .input-width {
            max-width: 300px;
        }
    }
    .footer {
        height: 44px;
        background: #f7f7f7;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding-left: 20px;
        padding-right: 20px;
    }
}
</style>
